from django_redis import get_redis_connection

redis_con = get_redis_connection()
import json

TRANSACTION_LENGTH = 10


def list_iter(name):
    """
    自定义redis列表增量迭代
    :param name: redis中的name，即：迭代name对应的列表
    :return: yield 返回 列表元素
    """
    list_count = r.llen(name)
    for index in range(list_count):
        yield r.lindex(name, index)

""":arg

# 使用
for item in list_iter('list2'):  # 遍历这个列表
    print(item)



"""


def get_latest_transactin(stock_id):
    """
        从redis中获取最新交易对
    """
    namespace = "{0}:transaction".format(stock_id)
    length = redis_con.llen(namespace)
    data = redis_con.lrange(namespace, 0, length)
    return data


def add_transaction(stock_id, transaction):
    """
        添加交易对到redis
    """
    namespace = "{0}:transaction".format(stock_id)
    length = redis_con.llen(namespace)
    if length >= TRANSACTION_LENGTH:
        redis_con.rpop(namespace)
        redis_con.lpush(namespace, transaction)


def add_bookList(stock_id, order, buy):
    """
        深度信息添加或修改
    """
    namespace = "{0}:{1}".format(stock_id, buy)
    exist = redis_con.zrangebyscore(namespace, order.price, order.price)
    if len(exist) == 0:
        redis_con.zadd(namespace, {order.undealed: order.price})
    else:
        cur_count = json.loads(exist[0])
        redis_con.zrem(namespace, cur_count)
        total = cur_count + 100
        redis_con.zadd(namespace, {total: order.price})


def get_book_list(stock_id):
    """:arg
        返回交易深度信息
    """
    pass


def add_buy_order_set(stock_id, order):
    pass


def add_sell_order_set(stock_id, order):
    pass
